<template>
  <div class="kpi-configuration">
    <!-- KPI分析配置标题 -->
    <div class="section-header">
      <h2 class="section-title">KPI分析配置</h2>
      <p class="section-description">选择并启用您需要执行的KPI分析算法</p>
    </div>

    <!-- 模板卡片列表 -->
    <div class="template-cards-container">
      <div
        v-for="(group, industryCode) in groupedTemplates"
        :key="industryCode"
        class="template-card"
        :class="{ active: isTemplateEnabled(industryCode), disabled: !isTemplateEnabled(industryCode) }"
      >
        <!-- 卡片头部 -->
        <div class="card-header">
          <div class="card-title-section">
            <span class="industry-icon" :class="getIndustryClass(industryCode)">
              <el-icon><FolderOpened /></el-icon>
            </span>
            <div class="title-content">
              <h3 class="template-name">
                {{ getIndustryLabel(industryCode) }}行业模板
              </h3>
              <span class="algorithm-count">{{ group.length }} 个KPI算法</span>
            </div>
          </div>
          <div class="card-switch-section">
            <el-switch
              :model-value="isTemplateEnabled(industryCode)"
              :disabled="group.length === 0"
              @update:model-value="handleTemplateSwitchChange(industryCode, $event)"
              @click.stop
            />
            <span class="switch-label">
              {{ group.length === 0 ? "暂无算法" : (isTemplateEnabled(industryCode) ? "已启用" : "已禁用") }}
            </span>
          </div>
        </div>

        <!-- 卡片内容 -->
        <div class="card-content">
          <div class="template-description">
            <p>{{ getTemplateDescription(industryCode) }}</p>
          </div>
        </div>

        <!-- 详情规则按钮（仅当模板启用时显示） -->
        <div v-if="isTemplateEnabled(industryCode)" class="card-actions">
          <el-button
            type="primary"
            link
            size="small"
            @click="toggleTemplateDetails(industryCode)"
          >
            <span>详情规则</span>
            <el-icon style="margin-left: 4px">
              <ArrowDown v-if="expandedTemplates[industryCode]" />
              <ArrowRight v-else />
            </el-icon>
          </el-button>
        </div>

        <!-- KPI算法详情列表（展开时显示） -->
        <transition name="slide-toggle">
          <div v-show="expandedTemplates[industryCode] && isTemplateEnabled(industryCode)" class="kpi-algorithms-list">
            <div
              v-for="algorithm in group"
              :key="algorithm.id"
              class="kpi-algorithm-item"
              :class="{ enabled: algorithm.enabled, disabled: !algorithm.enabled }"
            >
              <div class="algorithm-content">
                <div class="algorithm-main">
                  <h4 class="algorithm-name">{{ algorithm.templateName }}</h4>
                  <p class="algorithm-description">
                    {{ algorithm.description || "暂无描述" }}
                  </p>
                </div>
                <div class="algorithm-switch">
                  <el-switch
                    v-model="algorithm.enabled"
                    :active-value="true"
                    :inactive-value="false"
                    @change="handleSwitchChange(algorithm)"
                    @click.stop
                  />
                  <span class="switch-status">
                    {{ algorithm.enabled ? "已启用" : "已禁用" }}
                  </span>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="group.length === 0" class="empty-state">
              <el-empty description="该行业模板暂无KPI算法" :image-size="80" />
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { FolderOpened, ArrowDown, ArrowRight } from "@element-plus/icons-vue";

export default {
  name: "KpiConfiguration",
  components: {
    FolderOpened,
    ArrowDown,
    ArrowRight,
  },
  setup() {
    // 展开的模板详情
    const expandedTemplates = ref({});

    // 行业选项
    const industryOptions = [
      { label: "系统", value: "system" },
      { label: "通用", value: "general" },
      { label: "汽车", value: "auto" },
      { label: "医药", value: "pharma" },
      { label: "电子", value: "electronics" },
    ];

    // KPI模板数据（系统预定义，用户只能启用/禁用）
    const templateData = reactive([
      {
        id: "1",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_001",
        templateName: "生产效率分析",
        industryCode: "system",
        metricConfig: "system",
        description: "系统默认的生产效率KPI分析算法，提供基础的性能指标计算功能，包括产能利用率、设备效率等核心指标",
        version: 1,
        enabled: true,
      },
      {
        id: "2",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_002",
        templateName: "质量指标分析",
        industryCode: "system",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateQualityMetrics",
        description: "质量相关的KPI分析算法，统计产品合格率、不良品率、返工率等质量指标",
        version: 1,
        enabled: false,
      },
      {
        id: "3",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_003",
        templateName: "成本效益分析",
        industryCode: "system",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateCostMetrics",
        description: "成本效益相关的KPI分析算法，计算生产成本、物料成本、人工成本等经济指标",
        version: 1,
        enabled: true,
      },
      {
        id: "4",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_004",
        templateName: "通用行业产能分析",
        industryCode: "general",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateGeneralCapacity",
        description: "适用于通用行业的产能分析算法，提供标准化的产能利用率、设备稼动率等指标计算",
        version: 1,
        enabled: false,
      },
      {
        id: "5",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_005",
        templateName: "通用行业效率分析",
        industryCode: "general",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateGeneralEfficiency",
        description: "通用行业的生产效率分析算法，计算整体生产效率、工序效率等关键指标",
        version: 1,
        enabled: true,
      },
      {
        id: "6",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_006",
        templateName: "汽车行业产能利用率",
        industryCode: "auto",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateAutoCapacity",
        description: "专门为汽车制造行业设计的产能利用率分析算法，包含生产线产能、设备利用率等专业指标",
        version: 1,
        enabled: false,
      },
      {
        id: "7",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_007",
        templateName: "汽车行业质量合格率",
        industryCode: "auto",
        metricConfig: "com.aps.algorithm.service.KpiService.calculateAutoQuality",
        description: "汽车行业质量合格率分析算法，统计产品质量检测合格率、不良品率等质量指标",
        version: 1,
        enabled: true,
      },
      {
        id: "8",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_008",
        templateName: "医药行业合规性分析",
        industryCode: "pharma",
        metricConfig: "com.aps.algorithm.service.KpiService.calculatePharmaCompliance",
        description: "针对医药制造行业的合规性分析算法，重点关注GMP合规性、批次追溯等合规指标",
        version: 1,
        enabled: false,
      },
      {
        id: "9",
        tenantId: "tenant001",
        templateCode: "TEMPLATE_009",
        templateName: "医药行业生产效率",
        industryCode: "pharma",
        metricConfig: "com.aps.algorithm.service.KpiService.calculatePharmaEfficiency",
        description: "医药行业生产效率分析算法，计算生产效率、设备利用率等关键性能指标",
        version: 1,
        enabled: true,
      },
    ]);

    // 按行业分组的计算属性
    const groupedTemplates = computed(() => {
      const groups = {};
      templateData.forEach((template) => {
        const code = template.industryCode || "system";
        if (!groups[code]) {
          groups[code] = [];
        }
        groups[code].push(template);
      });

      // 确保所有行业都有分组（即使没有数据）
      industryOptions.forEach((option) => {
        if (!groups[option.value]) {
          groups[option.value] = [];
        }
      });

      return groups;
    });

    // 获取行业标签
    const getIndustryLabel = (code) => {
      const option = industryOptions.find((opt) => opt.value === code);
      return option ? option.label : code;
    };

    // 获取行业样式类
    const getIndustryClass = (code) => {
      const classMap = {
        system: "industry-system",
        general: "industry-general",
        auto: "industry-auto",
        pharma: "industry-pharma",
        electronics: "industry-electronics",
      };
      return classMap[code] || "industry-general";
    };

    // 获取模板描述
    const getTemplateDescription = (industryCode) => {
      const descriptions = {
        system: "系统默认KPI分析模板，提供基础的生产效率、质量指标、成本效益等核心KPI分析功能",
        general: "适用于通用行业的KPI分析模板，提供标准化的产能分析、效率分析等通用指标计算",
        auto: "专门为汽车制造行业设计的KPI分析模板，包含产能利用率、质量合格率等专业指标",
        pharma: "针对医药制造行业的KPI分析模板，重点关注合规性、生产效率等关键指标",
        electronics: "适用于电子制造行业的KPI分析模板，提供电子行业特定的性能指标计算",
      };
      return descriptions[industryCode] || "行业KPI分析模板";
    };

    // 判断行业模板是否启用（至少有一个算法启用）
    const isTemplateEnabled = (industryCode) => {
      const group = groupedTemplates.value[industryCode] || [];
      return group.some((algorithm) => algorithm.enabled);
    };

    // 处理模板开关变化
    const handleTemplateSwitchChange = (industryCode, enabled) => {
      const group = groupedTemplates.value[industryCode] || [];
      
      // 如果模板下没有算法，提示用户
      if (group.length === 0) {
        ElMessage.warning(`${getIndustryLabel(industryCode)}行业模板暂无KPI算法，无法启用`);
        return;
      }
      
      if (enabled) {
        // 启用模板：启用所有算法
        group.forEach((algorithm) => {
          algorithm.enabled = true;
        });
        ElMessage.success(`${getIndustryLabel(industryCode)}行业模板已启用`);
      } else {
        // 禁用模板：禁用所有算法
        group.forEach((algorithm) => {
          algorithm.enabled = false;
        });
        // 关闭详情展开
        expandedTemplates.value[industryCode] = false;
        ElMessage.success(`${getIndustryLabel(industryCode)}行业模板已禁用`);
      }
    };

    // 切换模板详情展开/收起
    const toggleTemplateDetails = (industryCode) => {
      expandedTemplates.value[industryCode] = !expandedTemplates.value[industryCode];
    };

    // 处理算法开关变化
    const handleSwitchChange = (algorithm) => {
      ElMessage.success(
        `KPI算法 "${algorithm.templateName}" 已${algorithm.enabled ? "启用" : "禁用"}`
      );
    };

    // 获取配置数据
    const getConfigData = () => {
      // 转换 enabled 字段为字符串格式（用于导出和保存）
      const templates = templateData.map((template) => ({
        ...template,
        enabled:
          typeof template.enabled === "boolean"
            ? template.enabled
              ? "1"
              : "0"
            : template.enabled,
      }));

      return {
        templates: templates,
      };
    };

    // 加载配置数据
    const loadConfigData = (data) => {
      if (data.templates) {
        templateData.splice(0, templateData.length, ...data.templates);
        // 转换 enabled 字段为布尔值（用于开关组件显示）
        templateData.forEach((template) => {
          if (typeof template.enabled === "string") {
            template.enabled = template.enabled === "1";
          }
        });
      }
    };

    // 验证配置
    const validateConfig = () => {
      const errors = [];

      // 验证模板数据
      if (templateData.length === 0) {
        errors.push("至少需要配置一个KPI算法");
      }

      return {
        valid: errors.length === 0,
        errors,
      };
    };

    // 重置配置
    const resetConfig = () => {
      templateData.forEach((template) => {
        template.enabled = false;
      });
      // 关闭所有详情展开
      expandedTemplates.value = {};
    };

    return {
      // 展开状态
      expandedTemplates,

      // 选项
      industryOptions,

      // 数据
      templateData,
      groupedTemplates,

      // 方法
      getIndustryLabel,
      getIndustryClass,
      getTemplateDescription,
      isTemplateEnabled,
      handleTemplateSwitchChange,
      toggleTemplateDetails,
      handleSwitchChange,

      // 配置方法
      getConfigData,
      loadConfigData,
      validateConfig,
      resetConfig,
    };
  },
};
</script>

<style scoped>
.kpi-configuration {
  padding: 0;
}

.section-header {
  margin-bottom: 30px;
  text-align: center;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: #714b67;
  margin-bottom: 10px;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.section-description {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 模板卡片容器 */
.template-cards-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-top: 20px;
  align-items: start; /* 确保每个卡片独立控制高度，不受其他卡片影响 */
  grid-auto-rows: min-content; /* 每行高度由内容决定，不拉伸 */
}

/* 模板卡片 */
.template-card {
  background: #ffffff;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: visible; /* 改为 visible，确保展开内容可见 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column; /* 使用 flex 布局，确保内容垂直排列 */
  height: auto; /* 高度自适应 */
  min-height: auto; /* 最小高度由内容决定 */
  align-self: start; /* 确保每个卡片独立控制高度，不受同一行其他卡片影响 */
}

.template-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #714b67 0%, #922575 100%);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.template-card.active::before {
  transform: scaleX(1);
}

.template-card:hover {
  border-color: #714b67;
  box-shadow: 0 4px 16px rgba(113, 75, 103, 0.15);
  transform: translateY(-2px);
}

.template-card.active {
  border-color: #714b67;
  background: linear-gradient(135deg, #ffffff 0%, #faf9fb 100%);
}

.template-card.disabled {
  opacity: 0.7;
  background: #f5f7fa;
}

.template-card.disabled .template-name {
  color: #909399;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.card-title-section {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.industry-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.industry-icon.industry-system {
  background: linear-gradient(135deg, #714b67 0%, #922575 100%);
  color: #ffffff;
}

.industry-icon.industry-general {
  background: linear-gradient(135deg, #e8f4f8 0%, #d1e9f0 100%);
  color: #017fa5;
}

.industry-icon.industry-auto {
  background: linear-gradient(135deg, #fff4e6 0%, #ffe0b3 100%);
  color: #e67e22;
}

.industry-icon.industry-pharma {
  background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
  color: #27ae60;
}

.industry-icon.industry-electronics {
  background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
  color: #8e44ad;
}

.title-content {
  flex: 1;
  min-width: 0;
}

.template-name {
  font-size: 18px;
  font-weight: 600;
  color: #714b67;
  margin: 0 0 6px 0;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.template-card.disabled .template-name {
  color: #909399;
}

.algorithm-count {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  display: inline-block;
}

.card-switch-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 6px;
  flex-shrink: 0;
}

.switch-label {
  font-size: 12px;
  color: #909399;
}

.template-card.active .switch-label {
  color: #714b67;
  font-weight: 500;
}

/* 卡片内容 */
.card-content {
  margin-bottom: 16px;
}

.template-description {
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
  border-left: 3px solid #714b67;
}

.template-description p {
  margin: 0;
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}

/* 卡片操作按钮 */
.card-actions {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

/* KPI算法列表 */
.kpi-algorithms-list {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 2px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* KPI算法项 */
.kpi-algorithm-item {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.kpi-algorithm-item.enabled {
  background: linear-gradient(135deg, #ffffff 0%, #faf9fb 100%);
  border-color: #714b67;
  box-shadow: 0 2px 8px rgba(113, 75, 103, 0.1);
}

.kpi-algorithm-item.disabled {
  background: #f5f7fa;
  border-color: #dcdfe6;
  opacity: 0.8;
}

.algorithm-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.algorithm-main {
  flex: 1;
  min-width: 0;
}

.algorithm-name {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.kpi-algorithm-item.enabled .algorithm-name {
  color: #714b67;
}

.algorithm-description {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
  margin: 0;
}

.algorithm-switch {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  flex-shrink: 0;
  padding-left: 16px;
  border-left: 1px solid #e4e7ed;
}

.switch-status {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
}

.kpi-algorithm-item.enabled .switch-status {
  color: #714b67;
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  padding: 20px;
  text-align: center;
}

/* 过渡动画 */
.slide-toggle-enter-active,
.slide-toggle-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-toggle-enter-from,
.slide-toggle-leave-to {
  max-height: 0;
  opacity: 0;
  margin-top: 0;
  padding-top: 0;
}

.slide-toggle-enter-to,
.slide-toggle-leave-from {
  max-height: 2000px;
  opacity: 1;
  margin-top: 16px;
  padding-top: 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .template-cards-container {
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  }
}

@media (max-width: 768px) {
  .template-cards-container {
    grid-template-columns: 1fr;
  }

  .algorithm-content {
    flex-direction: column;
    gap: 12px;
  }

  .algorithm-switch {
    border-left: none;
    border-top: 1px solid #e4e7ed;
    padding-left: 0;
    padding-top: 12px;
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
  }
}
</style>
